#!/bin/awk -f
## Synopsis: th2tm [-elist ELISTFILE || -0]
BEGIN{
  efn="th.inp";
  if(ARGV[1]=="-0"){
    efn="";
  }
  if(ARGV[1]=="-elist"){
    efn=ARGV[2];
    delete ARGV[1]; delete ARGV[2];
  }
  ARGC=1; # no input
  if(efn!=""){ethmin=100000}else{ethmin=0};
  if(efn=="th.inp"){
    fn="mktm.def";
    while(getline<fn){
      if($1=="rootname"){rn=$2"x2"};
      if($1=="thdir"){thdir=$2};
    }close(fn);
# th.def is supposed to be a copy of "tham", output of thfit. Format:
# coef i ENERGY COEF_NAME
    fn=thdir"/th.def";
    while(getline<fn){
      if($1=="coef"){
	ec[$4]=$3;
	print "coef "$4" E="$3;
      }
    }close(fn);
    j=0;
    while(getline<efn){
      j++;
      if(j==1){
	for(i=1;i<=NF;i++){
	  name[i]=$i;
	}
      }else{
	eth=0; for(i=1;i<=NF-1;i++){
	  if(ec[name[i]]!="")eth+=$i*ec[name[i]];
	}
	tn=$(NF);
	if(tn~/M/){
	  sub(/M/,"",tn);
	  eth=eth*2;
	};
	et[tn]=eth;
	if(eth<ethmin){ethmin=eth};
      }
    }
    close(fn);
  }else if (efn!=""){
    j=0;
    while(getline<efn){
      if($0!~/^ *\#/){
	j++;
	tn=$1; eth=$2;
	if(tn~/M/){
	  sub(/M/,"",tn);
	  eth=eth*2;
	};
	et[tn]=eth;
	if(eth<ethmin){ethmin=eth};
      }
    }
    close(fn);
  }
  for(i in et){if(et[i]==ethmin){j=i;if(i!~/L/){j="M"i};fnmin=fnmin" "j}};
  exit;
}
END{
  fno="TM";
  fn="sTM";
  print "transfer matrix -> TM";
  getline<fn;
  mdim=$1;
  if(efn=="")fnmin="-"; # dont want to print all
  print mdim" # dimension; EREF="ethmin/2" TREF=("fnmin") EFILE="efn > fno;
  for(i=1;i<=mdim;i++){
    for(j=1;j<=mdim;j++){
      getline<fn;
      line=$0
      n=$1; m=n;
      if(i==j){
	m++; eii=(et[i]-ethmin)/2;
      }      
      printf m" ">>fno;
      if(i==j){printf " 1 "eii>>fno}
#      print i,j,n,m;
      for(k=2;k<=n+1;k++){
	split($k,a,"*");
#	print a[1],a[2];
	x=(et[a[2]]-ethmin)/2;
	printf " "a[1]" "x>>fno;
      }
      print "  <"line>>fno;
    }
  }
}
